<template>
  <CloudDialog
    v-model:visible="visible"
    title="添加节点"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-open="handleOpen"
    :before-close="handleClose">
    <a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
      <a-form-item label="节点名称" field="name" hide-asterisk>
        <a-input
          v-model="formState.name"
          :max-length="32"
          show-word-limit
          placeholder="请输入节点名称"></a-input>
      </a-form-item>
      <a-form-item label="区域" field="region_id" hide-asterisk>
        <a-select
          v-model="formState.region_id"
          :options="areaListOptions"
          placeholder="请选择区域"></a-select>
      </a-form-item>
      <a-form-item label="节点层级" field="cascade_level" hide-asterisk>
        <template #label>
          <div class="flex gap-x-1 items-center">
            <span>节点层级</span>
            <a-tooltip :content-style="{ 'max-width': '509px' }">
              <i-icons-question class="question-icon" />
              <template #content>
                <span>
                  1. L2 节点负责回源，L1 节点自动从 L2 节点获取源站数据。<br />
                  2. 如果没有 L2 节点，L1 节点直接向源站请求回源。
                </span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-radio-group v-model="formState.cascade_level">
          <a-radio :value="1">L1</a-radio>
          <a-radio :value="2">L2</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-if="formState.cascade_level === 1"
        label="加入解析"
        field="enable_resolve"
        hide-asterisk>
        <template #label>
          <div class="flex gap-x-1 items-center">
            <span>加入解析</span>
            <a-tooltip>
              <i-icons-question class="question-icon" />
              <template #content>
                <span>
                  1. 立即加入，该节点将参与链路解析。
                  <br />
                  2. 暂不加入，该节点则不会参与链路解析。
                </span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-radio-group v-model="formState.enable_resolve">
          <a-radio :value="true">立即加入</a-radio>
          <a-radio :value="false">暂不加入</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item field="cache_path" hide-asterisk>
        <template #label>
          <div class="flex gap-x-1 items-center">
            <span>文件缓存路径</span>
            <a-tooltip :content-style="{ 'max-width': '509px' }">
              <i-icons-question class="question-icon" />
              <template #content>
                <span>
                  缓存路径请勿设置在 /opt/srv-biz 目录下，否则将造成程序更新异常
                  。</span
                >
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-input
          v-model="formState.cache_path"
          placeholder="请输入文件缓存路径"></a-input>
      </a-form-item>
      <a-form-item
        label="磁盘空间"
        field="cache_size"
        validate-trigger="blur"
        hide-asterisk>
        <a-input-number
          v-model="formState.cache_size"
          :controls="true"
          :precision="0"
          :max-length="13"
          class="cloud-input-number"
          style="border-top-left-radius: 0px"
          placeholder="请输入磁盘空间">
          <template #append>
            <a-select
              v-model="unit"
              :options="diskOptions"
              class="bg-transparent! border-none! rounded-tl-none rounded-bl-none!"></a-select>
          </template>
        </a-input-number>
      </a-form-item>
    </a-form>
  </CloudDialog>
</template>
<script lang="ts" setup>
import { addApiNodeApi } from '@/apis/modules/node/node'
import { diskOptions } from '@/constants'
import useGroupArea from '@/views/site/hooks/useGroupArea'
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
// import { useCookies } from '@vueuse/integrations/useCookies'
import { omit } from 'lodash-es'
const visible = defineModel<boolean>({ required: true })
const emit = defineEmits(['reload'])
const formRef = ref<FormInstance>()
const formState = ref({
  name: '',
  region_id: '',
  cache_path: '',
  cache_size: 200,
  enable_resolve: false,
  cascade_level: 1
})
const { areaListOptions, getOptions } = useGroupArea('region', {
  immediate: false
})

const unit = ref(2)

const rules = computed<Record<string, FieldRule>>(() => ({
  name: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('请输入节点名称')
      } else if (value.length < 4 || value.length > 32) {
        return callback('节点名称长度为4-32个字符')
      }
      callback()
    }
  },
  region_id: { required: true, message: '请选择区域' },
  cascade_level: { required: true },
  enable_resolve: { required: true },
  cache_path: {
    required: true,
    validator(value, callback) {
      const reg = /^\/(?:[^/]+(\/)?)*$/
      if (!value) {
        return callback('路径不能为空')
      }
      if (!reg.test(value)) {
        return callback('路径格式不正确')
      }
      callback()
    }
  },
  cache_size: cacheSizeRule(unit.value)
}))
// const {get,set } = useCookies()

const handleSubmit = async () => {
  const error = await formRef.value?.validate()
  if (error) return false

  const symbol = diskOptions.find((item) => item.value === unit.value)?.label
  const data = {
    ...omit(formState.value, ['cache_size']),
    cache_size: `${formState.value.cache_size}${symbol}`
  }
  return addApiNodeApi(data).then(() => {
    // set(
    //   CACHE_PATH_AND_DISK_STORE,
    //   {
    //     cache_path: formState.value.cache_path,
    //     cache_size: formState.value.cache_size,
    //     unit: unit.value
    //   },
    //   {
    //     maxAge: 90 * 60 * 60 * 24,
    //     path: '/'
    //   }
    // )
    ToastUtils.success('操作成功')
    visible.value = false
    emit('reload')
  })
}

const handleClose = () => {
  formRef.value?.resetFields()
}
const setDefaultCache = async () => {
  return new Promise((resolve) => {
    // const state = get(CACHE_PATH_AND_DISK_STORE)
    // if (!state?.cache_path) {
    // set(
    //   CACHE_PATH_AND_DISK_STORE,
    //   {
    //     cache_path: '/var/auth-cdn/cache',
    //     cache_size: 200,
    //     unit: 2
    //   },
    //   {
    //     maxAge: 90 * 60 * 60 * 24,
    //     path: '/'
    //   }
    // )
    formState.value.cache_path = '/var/auth-cdn/cache'
    formState.value.cache_size = 200
    unit.value = 2
    // }
    // else {
    //   formState.value.cache_path = state.cache_path
    //   formState.value.cache_size = state.cache_size
    //   unit.value = state.unit
    // }
    resolve(true)
  })
}
const handleOpen = async () => {
  setDefaultCache().then(getOptions)
  return true
}
</script>
<style lang="less" scoped>
:deep(.arco-input-outer > :first-child) {
  border-top-right-radius: 0px !important;
  border-bottom-right-radius: 0px !important;
}
:deep(.arco-form-item-label) {
  display: flex;
  width: 100%;
}
.arco-radio:first-child {
  padding-left: 0;
}
</style>
